<template>
  <div style="height: 100%">
    <layout id="dd"  ref="layout1" title="重命名" :closable="false" width="400px" :fullscreen="false"  @on-ok="doRename">
      <Input type="text"  v-model="newName" slot="content" placeholder="">
        <span slot="append">{{suffix}}</span>
      </Input>
    </layout>
    <layout id="aa" ref="layout2" title="重命名" :closable="false" width="200px" :fullscreen="false"  @on-ok="doRename">
      <Input type="text"  v-model="newName" slot="content" placeholder="">
      </Input>
    </layout>
    <layout ref="attrLayout" title="属性" :closable="false" width="400px" :fullscreen="false" :okButton="false">
      <CellGroup slot="content">
        <Cell title="类型">
          <span slot="extra">{{filetype}}</span>
        </Cell>
        <Cell title="路径">
          <span slot="extra">{{getPath()}}</span>
        </Cell>
        <Cell title="大小">
          <span slot="extra">{{size}}</span>
        </Cell>
      </CellGroup>
    </layout>
    <layout ref="uploadLayout" title="上传文件" @on-ok="add">
      <Upload
        slot="content"
        ref="upload"
        type="drag"
        :headers="header"
        :on-error="error"
        :on-success="success"
        :on-remove="remove"
        :on-format-error="formatError"
        :on-exceeded-size="exceededSize"
        :max-size="maxSize"
        :action="url">
        <div style="padding: 20px 0">
          <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
          <p>点击或拖拽文件上传</p>
        </div>
      </Upload>
    </layout>
    <Card style="padding: 15px;margin-bottom: 15px">
      在打开word,excel,ppt需要首页的office插件支持。
      <br>
      支持在线编辑支持word，excel，ppt。
      <br>
      收费使用：qq: 1005471232 ,微信：17521764260，手机号17521764260。价格 5000 永久不限服务器数量。
      <br>
      需要电脑安装Microsoft Office 2013以上版本
    </Card>
    <Card style="height: 100%;position: relative" @contextmenu.native="clearContextMenu($event,true)" @click.native="clearContextMenu($event,false)">
      <Spin fix v-if="spinShow">
        <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
        <div>Loading</div>
      </Spin>
      <Row style="height: 100%">
        <Col class="right">
          <Row style="padding: 10px 10px 0px 10px">
            <Col span="8">
              <Button @click="showUpload" icon="md-cloud-upload" type="primary">上传</Button>
            </Col>
            <Col span="8" style="float: right">
              <Input @on-search="filter" v-model="searchText" style="float: right;width: 200px;" search enter-button
                     placeholder="搜索文件"/>
            </Col>
          </Row>
          <Row style="padding: 10px">
            <a v-if="tagList.length!==1" style="margin-right: 2px" @click="back">返回上一级</a>
            <span v-if="tagList.length!==1">|</span>
            <span style="margin-left: 2px" :key="key" v-for="(item,key) in tagList">
              <a @click="to(key)" v-if="key!==tagList.length-1">{{item.name}}</a>
              <Icon v-if="key!==tagList.length-1" type="md-arrow-dropright"></Icon>
              <span v-if="key===tagList.length-1">{{item.name}}</span>
            </span>
            <div style="float: right">共{{data.length}}个文件</div>
          </Row>
          <Divider style="margin-top: 0px;margin-bottom: 5px"/>
          <Row style="height: calc(100% - 99px)">
            <Col span="24" :gutter="16" style="margin: 16px 0px;min-height: 120px">
              <div v-show="showMenu" class="menu" :style="offset">
                <li v-if="file.id!==undefined" class="ivu-dropdown-item" @click="select($event,'open')" name="open">打开</li>
                <li v-if="file.id!==undefined&&file.direction===false" class="ivu-dropdown-item" @click="select($event,'download')" name="download">下载</li>
                <li v-if="file.id!==undefined" class="ivu-dropdown-item" @click="select($event,'rename')" name="rename">重命名</li>
                <li v-if="file.id!==undefined" class="ivu-dropdown-item" @click="select($event,'delete')" name="delete" style="color: #ed5014">删除</li>
                <li v-if="file.id!==undefined" class="ivu-dropdown-item" @click="select($event,'attribute')" name="attribute">属性</li>
                <li v-if="file.id===undefined" class="ivu-dropdown-item" @click="select($event,'newFile')" name="newFile">新建文件夹</li>
                <li v-if="file.id===undefined" class="ivu-dropdown-item" @click="select($event,'refresh')" name="refresh">刷新</li>
              </div>
              <Row  :class="{'file active' : item.active,'file': !item.active}"
                    v-for="(item,key) in data"
                    @contextmenu.native="contentMenu($event,item)"
                    @click.native="selectFile($event,item)"
                    @dblclick.native="select($event,'open')"
                    :key="key">
                <svg v-if="getFileType(item.name)=='zip'||getFileType(item.name)=='rar'" class="icon" aria-hidden="true">
                  <use xlink:href="#icon-zip"></use>
                </svg>
                <svg v-if="getFileType(item.name)=='doc'||getFileType(item.name)=='docx'" class="icon" aria-hidden="true">
                  <use xlink:href="#icon-file-s-1"></use>
                </svg>
                <svg v-if="getFileType(item.name)=='xls'||getFileType(item.name)=='xlsx'" class="icon" aria-hidden="true">
                  <use xlink:href="#icon-file-b-2"></use>
                </svg>
                <svg v-if="getFileType(item.name)=='ppt'||getFileType(item.name)=='pptx'" class="icon" aria-hidden="true">
                  <use xlink:href="#icon-file-s-"></use>
                </svg>
                <svg v-if="getFileType(item.name)=='jpg'||getFileType(item.name)=='png'" class="icon" aria-hidden="true">
                  <use xlink:href="#icon-file-s-2"></use>
                </svg>
                <svg v-if="getFileType(item.name)=='txt'" class="icon" aria-hidden="true">
                  <use xlink:href="#icon-file-b-3"></use>
                </svg>
                <svg v-if="getFileType(item.name)=='pdf'" class="icon" aria-hidden="true">
                  <use xlink:href="#icon-file_pdf"></use>
                </svg>
                <svg v-if="getFileType(item.name)=='mp3'" class="icon" aria-hidden="true">
                  <use xlink:href="#icon-file-b-1"></use>
                </svg>
                <svg v-if="getFileType(item.name)=='mp4'" class="icon" aria-hidden="true">
                  <use xlink:href="#icon-file_video"></use>
                </svg>
                <svg v-if="getFileType(item.name)=='html'" class="icon" aria-hidden="true">
                  <use xlink:href=" #icon-file_html"></use>
                </svg>
                <svg v-if="getFileType(item.name)=='wjj'" class="icon" aria-hidden="true">
                  <use xlink:href="#icon-file-b-"></use>
                </svg>
                <svg v-if="getFileType(item.name)=='unKnow'" class="icon" aria-hidden="true">
                  <use xlink:href="#icon-file"></use>
                </svg>
                <div style="padding: 10px 15px 10px 15px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;user-select: none;-webkit-user-select: none">
                  {{item.name}}
                </div>
              </Row>
            </Col>
          </Row>
        </Col>
      </Row>
    </Card>
  </div>
</template>

<script>
import { list, deleteFile, rename, addFile } from '../../api/oss/file'
import layout from '_c/layout/layout.vue'
import { deleteAppendix, download } from '../../api/sys/appendix'
import config from '@/config'
import { getToken } from '../../libs/util'
import { previewFile } from '../../libs/preview'

const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro

export default {
  name: 'oss',
  components: { layout },
  data () {
    return {
      spinShow: true,
      url: baseUrl + 'sys/appendix/upload',
      maxSize: 102400,
      filetype: '',
      size: 0,
      newName: '',
      suffix: '',
      searchText: '',
      offset: {
        'top': '0px',
        'left': '0px',
        'position': 'fixed',
        'z-index': 1000
      },
      copyFile: [],
      file: {},
      showMenu: false,
      tagList: [{ path: '', name: '全部文件' }],
      data: [],
      default: []
    }
  },
  computed: {
    header: function () {
      return {
        'x-access-token': getToken()
      }
    }
  },
  methods: {
    to (index) {
      this.tagList.splice(index + 1, this.tagList.length - index)
      this.init()
    },
    back () {
      this.tagList.splice(this.tagList.length - 1, 1)
      this.init()
    },
    add () {
      let obj = {}
      obj.path = this.getPath()
      obj.list = this.$refs['upload'].fileList
      obj.direction = false
      addFile(obj).then(res => {
        this.init()
        this.$refs['uploadLayout'].hide()
      })
    },
    showUpload () {
      this.$refs['uploadLayout'].show()
      this.$refs['upload'].clearFiles()
    },
    exceededSize () {
      this.$Message.error('文件大小不能超过10M')
    },
    formatError () {
      this.$Message.error('不支持该文件格式')
    },
    error (response, file, fileList) {
      this.$Message.error(response)
    },
    success (response, file, fileList) {
      if (response.code === 200) {
        file.id = response.appendixId
      } else {
        this.$Message.error('文件上传失败')
        this.$refs['upload'].clearFiles()
      }
    },
    remove (file, fileList) {
      deleteAppendix(file.id).then(res => {
      })
    },
    doRename () {
      if (this.newName !== '') {
        rename({ id: this.file.id, newName: this.filetype === '文件夹' ? this.newName : this.newName + this.suffix }).then(res => {
          this.init()
          this.$refs['layout'].hide()
        })
      }
    },
    filter () {
      if (this.searchText !== '') {
        this.data = this.default.filter(item => {
          return item.name.indexOf(this.searchText) !== -1
        })
      } else {
        this.data = this.default
      }
    },
    getSuffix () {
      if (this.filetype === '文件') {
        this.suffix = this.file.name.substring(this.file.name.indexOf('.'))
      }
    },
    getName () {
      if (this.filetype === '文件夹') {
        this.newName = this.file.name
      } else {
        this.newName = this.file.name.substring(0, this.file.name.indexOf('.'))
      }
    },
    clearContextMenu (event, arg) {
      if (arg === true) {
        event.preventDefault()
        this.file = {}
        this.contentMenu(event, {})
      } else {
        this.contentMenu(event, {})
        this.showMenu = false
      }
    },
    contentMenu (event, item) {
      this.showMenu = true
      this.offset.left = event.clientX + 'PX'
      this.offset.top = event.clientY + 'px'
      this.setActive(item)
      event.stopPropagation()
      event.preventDefault()
    },
    selectFile (event, name) {
      this.contentMenu(event, name)
      this.showMenu = false
    },
    select (event, name) {
      if (name === 'open') {
        if (!this.file.direction) {
          previewFile(null, this.file.name, this.file.uuid, false)
        } else {
          this.tagList.push({ name: this.file.name, path: this.file.name })
          this.init()
        }
      } else if (name === 'rename') {
        this.getSuffix()
        this.getName()
        if (this.filetype === '文件') {
          this.$refs['layout1'].show()
        } else {
          this.$refs['layout2'].show()
        }
      } else if (name === 'delete') {
        deleteFile([this.file.id]).then(res => {
          this.init()
        })
      } else if (name === 'attribute') {
        this.$refs['attrLayout'].show()
      } else if (name === 'copy') {
        this.copyFile = []
        this.copyFile.push(this.file)
      } else if (name === 'download') {
        download(this.file.uuid).then(res => {})
      } else if (name === 'refresh') {
        this.init()
      } else if (name === 'newFile') {
        let obj = {}
        obj.path = this.getPath()
        obj.direction = true
        obj.name = '新建文件夹'
        addFile(obj).then(res => {
          this.init()
          this.$refs['uploadLayout'].hide()
        })
      }
      this.showMenu = false
      event.stopPropagation()
      event.preventDefault()
    },
    getFileType (name) {
      let allowsSuffix = ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'zip', 'rar', 'txt', 'mp3', 'mp4', 'html']
      let suffix = name.substring(name.lastIndexOf('.'), name.length)
      if (suffix.indexOf('.') === -1) {
        return 'wjj'
      }
      for (let i = 0; i < allowsSuffix.length; i++) {
        if (suffix.toLowerCase() === '.' + allowsSuffix[i]) {
          return allowsSuffix[i]
        }
      }
      return 'unKnow'
    },
    setActive (obj) {
      this.data.forEach(item => {
        if (item.id === obj.id) {
          item.active = true
          this.file = obj
          this.size = obj.size
          this.filetype = obj.direction ? '文件夹' : '文件'
        } else {
          item.active = false
        }
      })
    },
    getPath () {
      let path = ''
      this.tagList.forEach(item => {
        path = path + item.path + '/'
      })
      if (path !== '/') {
        path = path.substring(0, path.length - 1)
      }
      return path
    },
    init () {
      let path = this.getPath()
      list(path).then(res => {
        this.default = res.list
        this.filter()
        this.spinShow = false
      })
    }
  },
  mounted () {
    this.init()
  }
}
</script>

<style scoped>
  .file {
    width: 120px;
    float: left;
    text-align: center;
    padding: 20px 0px 10px 0px
  }

  .active {
    border: 1px solid #c3c3c3;
    background: #fff6fe;
  }

  .right {
    padding: 10px 15px 10px 15px;
    width: 100%;
    height: 100%;
  }

  /deep/ .ivu-card-body {
    height: 100%;
    padding: 0px;
  }

  .menu {
    position: fixed;
    border: 1px solid #cccccc;
    box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.5);
    width: 120px;
    position: absolute;
    background: white
  }

  .icon {
    width: 3em;
    height: 3em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
  }
  .demo-spin-icon-load{
    animation: ani-demo-spin 1s linear infinite;
  }
  @keyframes ani-demo-spin {
    from { transform: rotate(0deg);}
    50%  { transform: rotate(180deg);}
    to   { transform: rotate(360deg);}
  }
</style>
